package com.example.authserver.login;

import com.google.common.collect.Lists;
import com.taocares.security.core.Beans;
import com.taocares.security.core.authentication.AbstractAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider extends AbstractAuthenticationProvider {


    @Qualifier(Beans.DEFAULT_USER_DETAILS_SERVICE)
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void customAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {
        System.out.println("load user detail service && detail check");
        throw new BadCredentialsException("user.just.failed");
    }

    @Override
    public String getLoginType() {
        return "text";
    }

    @Override
    public UserDetailsService userDetailsService() {
        return new UserDetailsService(){
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return User.builder().username("dq123").password("123456").disabled(false).authorities(new SimpleGrantedAuthority("ADMIN")).build();
//                return new User("dq", "123", Lists.newArrayList(new SimpleGrantedAuthority("ADMIN")));
            }
        };
    }

    @Override
    public boolean isEncryption() {
        return false;
    }
}
